package org.cliff.message.platform.core.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

@Configuration
public class RestClientConfig {

    /**
     * 消息平台消息重发RestTemplate
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate mpResendRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        List<HttpMessageConverter<?>> resultMessageConverters = new LinkedList<>();
        for (HttpMessageConverter messageConverter : restTemplate.getMessageConverters()) {
            // XML导致在请求的accept 请求头里有xml相关的设定，导致响应为xml，用json更节省空间
            if (messageConverter instanceof MappingJackson2XmlHttpMessageConverter) {
                messageConverter = new Jaxb2RootElementHttpMessageConverter();
            }
            // 添加编码，防止中文乱码
            if (messageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter)messageConverter).setDefaultCharset(StandardCharsets.UTF_8);
            }
            resultMessageConverters.add(messageConverter);
        }
        restTemplate.setMessageConverters(resultMessageConverters);
        return restTemplate;
    }
}
